package com.lzy.securityResources.config;

import com.alibaba.fastjson.JSON;
import com.lzy.conf.JSONResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 无权访问配置(前后分离)
 */
@Component  // 交给spring管理
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setStatus(HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION);
        // 设置返回消息类型
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        // 返回给请求端
        String s = JSON.toJSONString(new JSONResult(HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION, "无权访问", null));
        PrintWriter out = httpServletResponse.getWriter();
        out.write(s);
        out.flush();
        out.close();
    }
}
